import objectAssign from 'object-assign';
import {loadFavouriteList, reloadFavouriteList} from "../actions/SysFavouriteActions";

const searchConditions = {
    count: 0, /**当前页实际的条数*/
    maxId: -1, /**已显示的最大id*/
    total: 0, /**总条数*/
    current: 0, /**已加载的条数*/
    pagesize: 15, /**每页加载的条数*/
    iscomplete: true, /**加载一页数据是否完成，如果一页数据没有完成，再滚动时，不加载数据*/
    dirId: "-1", /**目录，默认选中我的收藏*/
    favtype: "", /**收藏类型*/
    pagename: "" /**标题*/
};

export default class SearchFavourite {
    constructor(dispatch) {
        this._dispatch = dispatch;
    }

    static setConditions = (conditions) => {
        objectAssign(searchConditions, conditions);
    }

    static getConditions = () => {
        return {...searchConditions};
    }

    static setComplete = (iscomplete) => {
        objectAssign(searchConditions, {iscomplete});
    }

    static getComplete = () => {
        return searchConditions.iscomplete;
    }

    /**
     * 分页加载数据
     * @param params
     */
    loadPage = params => {
        let {iscomplete, current, total} = searchConditions;
        if (!iscomplete) {   //如果上一次加载数据还没有完成，那么就等0.5s后再试
            let that = this;
            window.setTimeout(function () {
                that.loadPage(params);
            }, 500);
        }

        if (total > 0 && current < total) {    //数据没有加载完，继续加载下一页的数据
            params = {...params, ...searchConditions};
            SearchFavourite.setComplete(false);
            this._dispatch(loadFavouriteList(params));   //加载下一页数据
        }
    }

    /**
     * 用于搜索，所以需要将一些数据重置
     * @param params
     */
    load = params => {
        let {iscomplete} = searchConditions;
        if (!iscomplete) {   //如果上一次加载数据还没有完成，那么就等0.5s后再试
            let that = this;
            window.setTimeout(function () {
                that.loadPage(params);
            }, 500);
        }

        params = {...params, ...searchConditions};
        SearchFavourite.setComplete(false);
        this._dispatch(reloadFavouriteList(params));   //加载下一页数据
    }
}
